import 'package:flutter/material.dart';  //dartUI包
import 'package:flutter_screenutil/flutter_screenutil.dart';  //屏幕自适应API
import 'dart:convert';  //json处理api
//import 'package:flutter/services.dart';  //
import 'package:shared_preferences/shared_preferences.dart';  //本地存储
import '../server/getdata.dart';  //引入接口调用类

/*
我的页面
*/
class ThirdPages extends StatefulWidget{
  @override
  _ThirdPagesState createState() => _ThirdPagesState();
}

//第三个页面
class _ThirdPagesState extends State<ThirdPages>{

  //创建监听事件
  FocusNode _focusUserName = FocusNode();
  FocusNode _focusPassWord = FocusNode();

  //创建全局key
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  //声明账号密码变量用于存储
  var _passWord = '';
  var _userName = '';
  String _user = '';

  //定义是否登录的状态判断变量
  bool _isLogin = false;

  //获取登陆状态
  Future<String> get() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _user = prefs.getString('userName');
    if(_user != null){
      _isLogin = true;
    }else{
      _user = '';
      _isLogin = false;
    }
    setState(() {
    });
  }

  //退出登录
  Future<String> remove() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('userName');
    prefs.remove('passWord');
    prefs.clear();
  }

  @override
  void initState(){
    //页面加载时添加监听事件
    get();
    _focusUserName.addListener(_focusNodeListener);
    _focusPassWord.addListener(_focusNodeListener);
    super.initState();
  }

  //定义当账号输入框获得焦点时移除密码框的焦点  密码同理
  Future _focusNodeListener() async{
    if(_focusUserName.hasFocus){
      _focusPassWord.unfocus();
    }
    if(_focusPassWord.hasFocus){
      _focusUserName.unfocus();
    }
  }

  //定义表达验证规则
  String validatePassWord(value){
    if(value.isEmpty){
      return '密码不能为空';
    }
    return null;
  }
  //定义表达验证规则
  String validateUserName(value){
    if(value.isEmpty){
      return '用户名不能为空';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {

    //用户信息存储到本地
    setLogicData(String key,String value) async{
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString(key, value);
    }

    ScreenUtil.instance = ScreenUtil(width:750,height:1334)..init(context);

    //头部
    Widget infoTop = Center(
      child: Text(
        _user,
      ),
    );

    //输入框组件
    Widget inputTextArea = Container(
      margin: EdgeInsets.only(left: 20,right: 20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        color: Colors.white
      ),
      child: Form(
        key: _formKey,
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            TextFormField(
              focusNode: _focusUserName,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                labelText: "请输入用户名",
                hintText: "请输入手机号",
                prefixIcon: Icon(Icons.person),
              ),
              validator: validateUserName,
              onSaved: (String value){
                _userName = value;
              },
            ),
            new TextFormField(
              focusNode: _focusPassWord,
              obscureText: true,
              decoration: InputDecoration(
                  labelText: "密码",
                  hintText: "请输入密码",
                  prefixIcon: Icon(Icons.lock),
              ),
              //密码验证
              validator:validatePassWord,
              //保存数据
              onSaved: (String value){
                _passWord = value;
              },
            )
          ],
        ),
      ),
    );

    //登录按钮组件
    Widget loginButtonArea  = Container(
      margin: EdgeInsets.only(left: 20,right: 20),
      height: 45.0,
      child: RaisedButton(
        color: Colors.blue[300],
        child: Text(
          "登录",
          style: Theme.of(context).primaryTextTheme.headline,
        ),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
        onPressed: (){

          //当点击登陆时移除两个输入框的焦点
          _focusUserName.unfocus();
          _focusPassWord.unfocus();

          //验证表单通过后执行保存操作
          if(_formKey.currentState.validate()){
            _formKey.currentState.save();

            var data = {'format':'json','userName':_userName.toString(),'passWord':_passWord.toString()};
            request('UserLogin',formData:data ).then((val){
              var info = json.decode(val.toString());

              //如果后台返回错误  执行的代码  提示错误信息
              if( info['status'] == 2 ){
                showDialog(
                    context: context,
                    builder: (_) => AlertDialog(
                      title: Text('提示'),
                      content: Text(info['message']),
                      actions: <Widget>[
                        FlatButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: Text('确定'),
                        )
                      ],
                    )
                );
              }else{

                setLogicData('userName',info['data']['userName'].toString());
                setLogicData('PassWord',info['data']['passWord'].toString());
                showDialog(
                    context: context,
                    builder: (_) => AlertDialog(
                      title: Text('登录成功'),
                      content: Text('欢迎您回来'),
                      actions: <Widget>[
                        FlatButton(
                          onPressed: () {
                            setState(() {
                              get();
                              _isLogin = true;
                            });
                            Navigator.of(context).pop();
                          },
                          child: Text('确定'),
                        )
                      ],
                    )
                );
              }
            });
          }
        },
      ),
    );


    //登录按钮组件
    Widget outButtonArea  = Container(
      margin: EdgeInsets.only(left: 20,right: 20),
      height: 45.0,
      child: RaisedButton(
        color: Colors.orange[300],
        child: Text(
          "退出登录",
          style: Theme.of(context).primaryTextTheme.headline,
        ),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
        onPressed: (){

          //当点击登陆时移除两个输入框的焦点
          _focusUserName.unfocus();
          _focusPassWord.unfocus();

          remove();
          showDialog(
              context: context,
              builder: (_) => AlertDialog(
                title: Text('退出登录成功'),
                content: Text('欢迎再来'),
                actions: <Widget>[
                  FlatButton(
                    onPressed: () {
                      setState(() {
                        get();
                        _isLogin = false;
                      });
                      Navigator.of(context).pop();
                    },
                    child: Text('确定'),
                  )
                ],
              )
          );
        },
      ),
    );

    //判断登录状态显示相应组件
    if(_isLogin){
      //拼接组件
      return Scaffold(
          appBar: AppBar(
              title: const Text("研招-我的")
          ),
          backgroundColor: Colors.white,
          body: new GestureDetector(
            onTap: (){
              _focusPassWord.unfocus();
              _focusUserName.unfocus();
            },
            child: new ListView(
              children: [
                new SizedBox(height: ScreenUtil().setHeight(60),),
                infoTop,
                new SizedBox(height: ScreenUtil().setHeight(80),),
                outButtonArea,
              ],
            )
          )
      );
    }else{
      //拼接组件
      return Scaffold(
          appBar: AppBar(
              title: const Text("研招-我的")
          ),
          backgroundColor: Colors.white,
          body: new GestureDetector(
              onTap: (){
                _focusPassWord.unfocus();
                _focusUserName.unfocus();
              },
              child: new ListView(
                children: [
                  new SizedBox(height: ScreenUtil().setHeight(70),),
                  inputTextArea,
                  new SizedBox(height: ScreenUtil().setHeight(80),),
                  loginButtonArea,
                ],
              )
          )
      );
    }

  }
}
